/**
 * 将File（Blob）对象转变为一个dataURL字符串， 即base64格式
 */
var fileToDataURL = function(file, onload, onerror) {
  var reader = new FileReader()
  reader.onload = function(ev) { onload(reader.result) }
  reader.onerror = function(event) { onerror({ errCode: 'COMPRESS_ERR' }) }
  reader.readAsDataURL(file)
}

/**
 * 将dataURL字符串转变为image对象，即base64转img对象
 */
var dataURLToImage = function(dataURL, onload, onerror) {
  var img = new Image()
  img.onload = function(ev) { onload(img) }
  img.onerror = function(event) { onerror({ errCode: 'COMPRESS_ERR' }) }
  img.src = dataURL
}

/**
 * 将base64转换为文件
 * @param dataurl
 * @returns {Blob}
 */
var dataURLtoFile = function(dataurl) {
  var arr = dataurl.split(',')
  var mime = arr[0].match(/:(.*?);/)[1]
  var bstr = atob(arr[1])
  var n = bstr.length
  var u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new Blob([u8arr], { type: mime })
}

/**
 * 采用二分逼近法压缩图片到指定范围内 单位 B
 * @param file
 * @param maxSize
 * @param minSize
 * @param onload
 * @param onerror
 */
export default function compress(file, maxSize, minSize, onload, onerror) {
  if (file.size < maxSize) {
    console.log('图片小于指定大小：' + maxSize + 'B, 不用压缩')
    return onload(file)
  }

  fileToDataURL(file, function(base64Url) {
    var canvas = document.createElement('canvas')
    var ctx = canvas.getContext('2d')

    dataURLToImage(base64Url, function(image) {
      canvas.width = image.width
      canvas.height = image.height
      ctx.clearRect(0, 0, canvas.width, canvas.height)
      ctx.drawImage(image, 0, 0, canvas.width, canvas.height)

      var compressFileSize = file.size
      var quality = 0.5
      var maxQuality = 1
      var minQuality = 0
      var compressFile = null

      while (compressFileSize > maxSize || compressFileSize < minSize) {
        var base64Codes = canvas.toDataURL(file.type, quality)
        compressFile = dataURLtoFile(base64Codes)
        compressFileSize = compressFile.size
        if (compressFileSize > maxSize) {
          maxQuality = quality
          quality = (maxQuality + minQuality) / 2
        }
        if (compressFileSize < minSize) {
          minQuality = quality
          quality = (maxQuality + minQuality) / 2
        }
      }
      console.log('压缩后大小：' + compressFile.size)
      onload(compressFile)
    }, onerror)
  }, onerror)
}
